<template>
  <div>
    <el-dialog v-model="dialogInfo.visible" :title="props.title" destroyOnClose>
      <div class="box">
        <div class="methodbox">
          <div class="label text-[#333] font-bold">选择共享方式</div>
          <div class="flex mt-[6px] val">
            <div class="flex bg-[#F4F4F3] rounded-[4px] box">
              <div
                class="text-[13px] py-[6px] px-[20px] cursor-pointer item"
                v-for="(item, index) in MethodList"
                :key="index"
                :class="curMehtodIndex === index ? 'active' : ''"
                @click="changeMethod(index)"
              >
                {{ item.label }}
              </div>
            </div>
          </div>
        </div>
        <div class="mt-[15px] mainbody" v-if="curMehtodIndex === 1">
          <div class="label">选择主体<span class="red">*</span></div>
          <div class="mt-[6px] w-[400px] val">
            <el-select v-model="value1" placeholder="Select" clearable>
              <template #label="{ label }">
                <span>{{ label }}</span>
              </template>
              <el-option v-for="item in accountAllCompanyInfo" :key="item.companyId" :value="item.companyId" :label="item.companyName">
                <template #default>
                  <span>{{ item.companyName }}</span>
                </template>
              </el-option>
            </el-select>
          </div>
        </div>
        <div class="mt-[15px] mainbody">
          <div class="label">选择账户<span class="red">*</span></div>
          <div class="mt-[6px] val">
            <!-- <div class="w-[400px] searchbox">
              <el-input type="text" placeholder="请输入账户名称/ID" suffix-icon="Search" />
            </div> -->
            <div class="w-full flex mt-[6px] h-[300px] overflow-y-hidden databox">
              <div class="w-full mr-[10px] border-solid border-[#DFE0E0] border-[1px] rounded-[4px] left">
                <div class="font-bold bg-[#F4F4F5] p-[8px] title">
                  <div class="text-[#333] tit" v-if="curMehtodIndex === 2">账户ID({{ accountNum }}/1000)</div>
                  <div class="text-[#333] font-bold tit" v-else-if="!viewAll">账户类型</div>
                  <div class="tit" v-else>
                    <span class="text-[#999]">账户类型</span>
                    <span class="relative top-[2px] px-[10px] arrow">
                      <el-icon><ArrowRight /></el-icon>
                    </span>
                    <span class="text-[#333]">巨量广告</span>
                  </div>
                </div>
                <div class="h-[262px] overflow-y-scroll p-[10px] cont">
                  <div class="listbox" v-if="curMehtodIndex !== 2 && !viewAll">
                    <el-checkbox-group v-model="selectGroup" @change="handleCheckboxChange">
                      <el-checkbox v-for="(item, index) in checkBoxList" :key="index" :value="item.value">
                        <template #default>
                          {{ item.title }}
                        </template>
                      </el-checkbox>
                    </el-checkbox-group>
                  </div>
                  <div class="listbox" v-if="curMehtodIndex !== 2 && viewAll"></div>
                  <div class="listbox h-full w-full" v-if="curMehtodIndex === 2">
                    <!-- 移除点击添加新输入框的逻辑 -->
                    <div class="h-[80%] w-[100%] pl-[10px] border border-[#DFE0E0] rounded-[4px] overflow-y-auto">
                      <div v-for="(inputValue, index) in inputList" :key="index" class="flex items-center mt-2 relative">
                        <span class="mr-[5px] w-[25px] text-right color-[#969aa0]">{{ index + 1 }}</span>
                        <el-input ref="inputRefs" v-model="inputList[index]" placeholder="请输入id" @keyup.enter="addInput" class="flex-grow pr-8">
                          <template #append v-if="inputList.length > 1">
                            <el-button icon="Close" circle size="small" @click.stop="removeInput(index)" />
                          </template>
                        </el-input>
                      </div>
                    </div>
                    <!-- 添加按钮 -->
                    <div class="flex justify-center mt-4">
                      <el-button type="primary" @click="addToSelected">添加到已选</el-button>
                    </div>
                  </div>
                </div>
              </div>
              <div class="w-[240px] ml-auto border-solid border-[#DFE0E0] border-[1px] rounded-[4px] shrink-0 right">
                <div class="bg-[#F4F4F5] p-[8px] flex justify-between items-center title">
                  <div class="text-[#333] font-bold tit">已选({{ selectNum }}/{{ selectNumMax }})</div>
                  <div class="text-[#409EFF] pointer" @click="clearSelected">清空</div>
                </div>
                <div class="h-[262px] overflow-y-scroll p-[10px] cont">
                  <!-- 动态渲染已选内容 -->
                  <div class="mt-[5px]" v-for="(item, index) in selectedItems" :key="index">{{ item }}</div>
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="handleCancel">取消</el-button>
          <el-button type="primary" :disabled="selectedItems.length === 0" @click="handleConfirm">确定</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { bpAssetManagementShare, getAccountAllCompanyInfo } from '@/api/advertisement/account/index';
import { useAppStore } from '@/store/modules/app';
import { ShareDpAssetManagementReq, AssetType, AccountInfoAccountType, ShareMode } from '@/api/advertisement/account/types';
import { ElInput } from 'element-plus';

const appStore = useAppStore();
const props = defineProps<{
  title: string;
  type: AssetType;
  appTenantId: string | number;
}>();

const queryParams = reactive(<ShareDpAssetManagementReq>{});

const dialogInfo = ref({
  visible: false
});

const curMehtodIndex = ref(0);

const selectNumMax = ref(100);

const viewAll = ref(false);

const selectGroup = ref([]);

const inputList = ref<string[]>(['']); // 存储所有输入框的值
const inputRefs = ref<InstanceType<typeof ElInput>[]>([]); // 存储输入框的引用
const selectedItems = ref<string[]>([]); // 存储已选内容

const selectNum = computed(() => {
  return selectedItems.value.length;
});

const MethodList = reactive([
  {
    value: ShareMode.BP_ALL_ACCOUNTS,
    label: '组织下的账户'
  },
  {
    value: ShareMode.COMPANY_ALL_ACCOUNTS,
    label: '主体下的账户'
  },
  {
    value: ShareMode.PART,
    label: '通过ID授权'
  }
]);

const value1 = ref<string>('');

const accountAllCompanyInfo = ref([]);
enum CheckBoxType {
  AD = 'AD'
}
const checkBoxList = [
  {
    title: '所有巨量广告账户',
    subTitle: '当前组织下所有及新增巨量广告可用',
    value: CheckBoxType.AD
  }
];

const accountNum = computed(() => {
  return inputList.value.length;
});

// 处理多选框选中状态变化
const handleCheckboxChange = (values: string[]) => {
  // 先清空已选列表
  selectedItems.value = [];
  // 遍历选中的值，将对应的 title 添加到已选列表
  values.forEach((value) => {
    const item = checkBoxList.find((item) => item.value === value);
    if (item) {
      selectedItems.value.push(item.title);
    }
  });
};

const handleShare = async () => {
  queryParams.organizationId = appStore.accountId;
  queryParams.instanceId = props.appTenantId;
  queryParams.shareMode = MethodList[curMehtodIndex.value].value;
  queryParams.assetType = props.type;
  if (curMehtodIndex.value === 0) {
    queryParams.allAccountsByBp = ['AD'];
  } else if (curMehtodIndex.value === 1) {
    queryParams.allAccountsByCompany = [
      {
        companyId: Number(value1.value),
        accountType: AccountInfoAccountType.AD
      }
    ];
  } else {
    queryParams.accountInfos = selectedItems.value.map((item) => {
      return {
        accountId: Number(item),
        accountType: AccountInfoAccountType.AD
      };
    });
  }
  console.log('queryParams', queryParams);
  const res = await bpAssetManagementShare(queryParams);
  resetQuery();
  dialogInfo.value.visible = false;
};

// 取消按钮点击事件
const handleCancel = () => {
  dialogInfo.value.visible = false;
  resetQuery();
  selectedItems.value = [];
  selectGroup.value = [];
  inputList.value = [''];
  value1.value = '';
};

// 确定按钮点击事件
const handleConfirm = async () => {
  await handleShare();
};

const getAccountCompanyInfo = async () => {
  if (accountAllCompanyInfo.value.length !== 0) {
    return;
  }
  const res = await getAccountAllCompanyInfo({
    accountId: appStore.accountId
  });
  accountAllCompanyInfo.value = res.rows;
  value1.value = res.rows[0].companyId;
};

const resetQuery = () => {
  queryParams.shareMode = null;
  queryParams.accountIds = null;
  queryParams.allAccountsByBp = null;
  queryParams.allAccountsByCompany = null;
  queryParams.assetType = null;
  queryParams.instanceId = null;
};

const changeMethod = async (i: number) => {
  if (selectedItems.value.length > 0) {
    try {
      // 弹出确认对话框
      await ElMessageBox.confirm('切换后，已选信息将不被保存，是否继续？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      });
      // 用户点击确定，继续切换
      selectedItems.value = [];
      selectGroup.value = []; // 清空多选框选中值
      resetQuery();
    } catch (error) {
      // 用户点击取消，不执行切换操作
      return;
    }
  }

  curMehtodIndex.value = i;
  if (i === 1) {
    getAccountCompanyInfo();
  }
};

const show = () => {
  dialogInfo.value.visible = true;
};
const hide = () => {
  dialogInfo.value.visible = false;
};

// 添加输入框
const addInput = () => {
  inputList.value.push('');
  // 使用 nextTick 确保 DOM 更新完成后聚焦新输入框
  nextTick(() => {
    const newInputIndex = inputList.value.length - 1;
    if (inputRefs.value[newInputIndex]) {
      inputRefs.value[newInputIndex].focus();
    }
  });
};

// 删除指定索引的输入框
const removeInput = (index: number) => {
  inputList.value.splice(index, 1);
  selectedItems.value.splice(index, 1);
};

// 添加到已选
const addToSelected = () => {
  const newItems = inputList.value
    .filter((input) => input.trim() !== '') // 过滤空输入
    .filter((input) => !selectedItems.value.includes(input.trim())); // 排除重复项
  const potentialTotal = selectedItems.value.length + newItems.length;
  // 检查是否超过最大数量
  if (curMehtodIndex.value === 3 && potentialTotal > 100) {
    ElMessageBox.alert('已选列表最多支持 100 个ID，请减少输入项', '提示', {
      type: 'warning'
    });
    return;
  }
  addInput();
  selectedItems.value = [...selectedItems.value, ...newItems];
};

// 清空已选
const clearSelected = () => {
  selectGroup.value = [];
  selectedItems.value = [];
  inputList.value = [''];
};
defineExpose({ show, hide });
</script>

<style lang="scss" scoped>
.methodbox {
  .val {
    .box {
      .item {
        border: 1px solid #f4f4f3;
        &:first-child {
          border-radius: 4px 0 0 4px;
        }
        &:last-child {
          border-radius: 0 4px 4px 0;
        }
        &.active {
          border: 1px solid #2a55e5;
          color: #2a55e5;
        }
      }
    }
  }
}
.databox {
  .title {
    border-bottom: 1px solid #dfe0e0;
    border-radius: 4px 4px 0 0;
  }
}
</style>
